package com.zhugang.week13.hash;

import java.util.*;

/**
 * @program algorithms
 * @description: groupAnagrams
 * @author: chanzhugang
 * @create: 2022/12/06 15:03
 */
public class GroupAnagrams {

    /**
     * 49 字母异位词分组
     * https://leetcode.cn/problems/group-anagrams/
     *
     * @param strs
     * @return
     */
    public List<List<String>> groupAnagrams(String[] strs) {
        /**
         * 排好序的字符串作为key， 本身作为value
         */
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            // 字符串不可变，所以转成字符数组，再转成字符串
            char[] array = str.toCharArray();
            Arrays.sort(array);
            String key = new String(array);
            // 没用过这个方法,看方法名也能猜出来含义
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<>(map.values());
    }
}